package com.oot.twitter;

import android.content.Intent;
import android.graphics.Path;
import android.os.Bundle;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.ProgressBar;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.markupartist.android.widget.PullToRefreshListView;
import com.oot.twitter.adapter.UsersListAdapter;
import com.oot.twitter.base.BaseActivity;
import com.oot.twitter.base.SimpleURI;
import com.oot.twitter.info.User;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;

public class UsersList extends BaseActivity implements OnItemClickListener, AbsListView.OnScrollListener {

	// Define direction of scroll
	private static final int DIRECTION_TOP    = 1;
	private static final int DIRECTION_NONE   = 0;
	private static final int DIRECTION_BOTTOM = -1;

	// Define listview
	private PullToRefreshListView list;
	private ArrayList<User>  users = new ArrayList<User>();
    protected UsersListAdapter ula;

    // Proterty to load this activity
    private SimpleURI uri;

    // Property for endless scroll list
    private String  since_id     = "-1";
    private String  max_id       = "-1";
	private int loadingDirection = DIRECTION_NONE;
	private int visibleThreshold = 0;
    private boolean isLoading    = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

		uri = (SimpleURI) GlobalData.paramIntent;

        // prepare interface
		setContentView(R.layout.userslist);
		prepareInterface();
    }

	/**
	 * Create new listview, apdater
	 * Set listener
	 */
	private void prepareInterface(){
		users = new ArrayList<User>();
		ula           = new UsersListAdapter(this, R.layout.user_item, users);

		list = (PullToRefreshListView)findViewById(R.id.users_list);
		list.setAdapter(ula);
		list.setOnItemClickListener(this);
		list.setOnRefreshListener(new PullToRefreshListView.OnRefreshListener() {
			public void onRefresh() {
				getDataFromServer(DIRECTION_TOP);
			}
		});
		list.setOnScrollListener(this);
	}

	/**
	 * set loading state and animation
	 * @param isLoading
	 */
	private void setLoading(boolean isLoading){
		this.isLoading = isLoading;
		ProgressBar progressBar = (ProgressBar)findViewById(R.id.empty);
		if (isLoading){
			progressBar.setVisibility(View.VISIBLE);
		}
		else
			progressBar.setVisibility(View.GONE);
	}


	/**
	 * Get data from server with custom param depend on direction
	 * @param direction
	 */
	private void getDataFromServer(int direction){
		// prepare params
		setLoading(true);
		loadingDirection = direction;
		switch (direction){
			case DIRECTION_BOTTOM:
				if (!since_id.equals("-1")){
					uri.getParams().put("since_id",since_id);
				}
				break;
			case DIRECTION_TOP:
				if (!max_id.equals("-1")){
					uri.getParams().put("max_id",max_id);
				}
				break;
		}
		ConnectionTwitter.asyncHttpClient.get(uri.getUrl(), uri.getParams(), new AsyncHttpResponseHandler(){
			@Override
			public void onSuccess(String s) {
				ArrayList<User> users;
				try{
					users = User.parseArray(new JSONArray(s));
				}catch (Exception e){
					System.out.println("Parse userslist array fail");
					users = new ArrayList<User>();
				}
				addMoreuser(users);
			}

			@Override
			public void onFinish() {
				setLoading(false);
			}

			@Override
			public void onFailure(Throwable throwable, String s) {
				super.onFailure(throwable, s);    //To change body of overridden methods use File | Settings | File Templates.
			}
		});
	}

	/**
	 * Event handler for item click in listview
	 * @param useradapter
	 * @param arg1
	 * @param position
	 * @param arg3
	 */
	public void onItemClick(AdapterView<?> useradapter, View arg1, int position, long arg3) {
		User user = (User)useradapter.getItemAtPosition(position);
		Intent showInfo = new Intent(UsersList.this, OtherPersonProfile.class);
		Bundle param    = new Bundle();
		/**
		 * TODO
		 * Tranfer param to Ngoc's Intent
		 */
		param.putString("id", user.getUser_id());
		param.putString("userlist", "1");
		showInfo.putExtras(param);
		showInfo.putExtra("avarta", user.getAvatarBitmap());
		startActivity(showInfo);
		
		
		System.out.println(user.getUser_id());
	}

    public void onScrollStateChanged(AbsListView absListView, int i) {
    }

	/**
	 * Create endless listview
	 * @param view
	 * @param firstVisibleItem
	 * @param visibleItemCount
	 * @param totalItemCount
	 */
    public void onScroll(AbsListView view, int firstVisibleItem,int visibleItemCount, int totalItemCount) {
        if (isLoading) return;
        boolean isNeedLoad = (firstVisibleItem + visibleItemCount + visibleThreshold>= totalItemCount);
        if (!isNeedLoad) return;

		System.out.println("NEED LOAD MORE");
		getDataFromServer(DIRECTION_BOTTOM);
    }

	/**
	 * Add more user to listview
	 * @param users
	 */
	private void addMoreuser(ArrayList<User> users){
		 // Add more user to adapter
		int n = users.size();
		for (int i=0; i<n; i++){
			if (loadingDirection == DIRECTION_BOTTOM)
				ula.add(users.get(i));
			else
				ula.insert(users.get(i),i);
		}

		// Change the state of pull to refresh list
		ula.setNotifyOnChange(true);
		if (loadingDirection == DIRECTION_TOP)
			list.onRefreshComplete();

		// Determine new since_id and max_id
		updateSinceMax();
	}

	/**
	 * Update since_id and max_id
	 */
	protected void updateSinceMax(){
		int m = ula.getCount();
		if (m < 1) return;
		max_id   = ula.getItem(0).getOrder_id();
		since_id = ula.getItem(m-1).getOrder_id();
	}

}